package com.net.http
{
	import com.net.Event.HttpEvent;
	import com.net.HttpServer;
	import com.net.requesthandler.IRequestHandler;
	import com.net.requesthandler.resourceRequestHandler;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	public class HttpRequest extends EventDispatcher
	{
		private var socket:Socket;
		
		private var handler:IRequestHandler;//处理此请求
		
		private var requeststream:RequestStream;//请求的输入输出流
		
		private var request_header:RequestHeader;//此请求的请求头
		
		/**
		 * 传入一个socket来处理一个请求链接
		 * 
		 */
		public function HttpRequest(s:Socket)
		{
			socket=s;
			
			requeststream=new RequestStream(socket);
			
			socket.addEventListener(ProgressEvent.SOCKET_DATA,on_data);
			socket.addEventListener(Event.CLOSE,on_closed);
			socket.addEventListener(IOErrorEvent.IO_ERROR,on_error);
		}
		
		/**
		 * 关闭此对话
		 */
		public function close():void{
			requeststream.close();
			if(socket.connected){
				socket.close();
			}
			this.dispatchEvent(new HttpEvent(HttpEvent.SESSION_CLOSE));
		}
		
		/**
		 * 查看是否是活动的连接
		 */
		public function get isConnect():Boolean{
			return socket.connected;
		}
		
		/**
		 * 此连接的输入输出流
		 */
		public function getRequestStream():RequestStream{
			return requeststream;
		}
		
		
		/**
		 * 此请求的请求头
		 */
		public function getRequestHeader():RequestHeader{
			return request_header;
		}
		
		//数据到达
		private function on_data(event:ProgressEvent):void{
			if(request_header==null){
				request_header=new RequestHeader(requeststream.readLine());//将第一行参数传入来建立请求头
				var tempParameter:String=requeststream.readLine();
				while(tempParameter!=null){
					if(tempParameter==""){
						break;
					}
					request_header.pushParmeter(tempParameter);
					tempParameter=requeststream.readLine();
				}
				
				//检查资源请求链接是否注册有自定义处理对象
				handler=HttpServer.getIRequestHandler(request_header.getFilePath());
				if(handler==null){
					handler=new resourceRequestHandler();
				}
				handler.setRequest(this)
			}
			
			//请求头剩余部分则为post数据
			if(socket.connected && socket.bytesAvailable>0){
				requeststream.ByteArrive();
			}
		}
		
		//连接断开  关闭对话
		private function on_closed(event:Event):void{
			close();
		}
		
		//连接出现错误
		private function on_error(event:IOErrorEvent):void{
			socket.close();
		}
	}
}